package com.rainwood.water_authority.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

import com.android.zxing.android.QRCodeCaptureActivity;
import com.rainwood.water_authority.R;
import com.rainwood.water_authority.aop.SingleClick;
import com.rainwood.water_authority.base.MyBaseActivity;
import com.rainwood.water_authority.event.PanDianEvent;
import com.rainwood.water_authority.http.request.InventoryCommitApi;
import com.rainwood.water_authority.http.request.InventoryDetailApi;
import com.rainwood.water_authority.http.request.InventoryMaterialApi;
import com.rainwood.water_authority.http.request.PanDianDetilsApi;
import com.rainwood.water_authority.http.request.ShouLiaoDetilsUpdateApi;
import com.rainwood.water_authority.http.response.PanDianListBean;
import com.rainwood.water_authority.http.response.PangDianBean;
import com.rainwood.water_authority.http.response.SimpleResultBean;
import com.rainwood.water_authority.other.IntentKey;
import com.rainwood.water_authority.ui.adapter.InventoryDetailBaseAdapter;
import com.rainwood.water_authority.ui.dialog.MessageDialog;
import com.rainwood.water_authority.util.Constants;
import com.rainwood.water_authority.util.JsonUtils;
import com.rainwood.water_authority.util.ListUtils;
import com.rainwood.water_authority.util.LogUtils;
import com.rainwood.water_authority.util.SharePrenceHelper;
import com.sxs.easyhttp.EasyHttp;
import com.sxs.easyhttp.listener.HttpCallback;
import com.sxs.tools.base.BaseAdapter;
import com.sxs.tools.permission.OnPermission;
import com.sxs.tools.permission.Permission;
import com.sxs.tools.permission.XXPermissions;
import com.sxs.tools.widget.layout.SettingBar;
import com.sxs.tools.widget.layout.WrapRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author sxs
 * @date :2020/9/28
 * @desc: 单据盘点
 */
public final class PanDianListAct extends MyBaseActivity
        implements BaseAdapter.OnChildClickListener {

    public static void start(Context context, String id) {
        Intent intent = new Intent(context, PanDianListAct.class);
        intent.putExtra(IntentKey.ID, id);
        context.startActivity(intent);
    }
    public static void start02(Context context, String id) {
        Intent intent = new Intent(context, PanDianListAct.class);
        intent.putExtra("historyid", id);
        context.startActivity(intent);
    }

    private SettingBar mInventoryNumberView;
    private SettingBar mMonthBarView;
    private SettingBar mTypeBarView;
    private WrapRecyclerView mInventoryListView;
    private String pandianid;
    private InventoryDetailBaseAdapter mInventoryDetailAdapter;
   private String orderId;

    @Override
    protected int getLayoutId() {

        return R.layout.activity_inventory_detail;
    }

    @Subscribe
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//订阅
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {
        mInventoryNumberView = findViewById(R.id.sb_inventory_no);
        mMonthBarView = findViewById(R.id.sb_month);
        mTypeBarView = findViewById(R.id.sb_type);
        mInventoryListView = findViewById(R.id.rv_for_inventory_list);
        mInventoryDetailAdapter = new InventoryDetailBaseAdapter(this);
        mInventoryDetailAdapter.setOnChildClickListener(R.id.btn_outbound, this);
        mInventoryListView.setAdapter(mInventoryDetailAdapter);
        setOnClickListener(R.id.btn_scan_outbound);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        //来源扫码
        if (getString(IntentKey.ID)!=null){
            requestDatum();
        }else {
            //来源历史记录
            String history=getString("historyid");
            EventBus.getDefault().post(new PanDianEvent(history));
        }

    }

    private HashMap<String, String> substring(String id) {
        HashMap<String, String> hashMap = new HashMap<>();
        String no = id.substring(3, id.indexOf("&", 0));
        String type = id.substring(id.indexOf("=", 5) + 1, id.indexOf("&direction", 0));
        String direction = id.substring(id.indexOf("&direction=") + 11, id.length());
        hashMap.put("no", no);
        hashMap.put("type", type);
        hashMap.put("direction", direction);
        return hashMap;
    }

    private void requestDatum() {
        String id = getString(IntentKey.ID);
        HashMap hashMap = substring(id);
        EasyHttp.post(this)
                .api(new InventoryDetailApi()
                        .setCheckId(hashMap))
                .request(new HttpCallback<PangDianBean>(this) {
                    @Override
                    public void onSucceed(PangDianBean result) {
                        if (result.getData() != null && result.getData().getInfo() != null) {


//                            if (ListUtils.getSize(result.getData().getInfo()) == 0) {
//                                TextView headView = mInventoryListView.addHeaderView(R.layout.picker_item);
//                                headView.setText("暂无物资数据");
//                                return;
//                            }
                            EventBus.getDefault().post(new PanDianEvent(result.getData().getInfo().get(0).getId()));

                        }
                    }
                });
    }

    //保存扫描盘口之后的数据缓存
    private void savepandian(PanDianListBean.DataBean.InfoBean bean) {
        List<PanDianListBean.DataBean.InfoBean> list=new ArrayList<>();
        String pandianlist = SharePrenceHelper.getStringData("pandian");
        if (pandianlist != null && !pandianlist.equals("")) {
            try {
                 list = JsonUtils.jsonToArray(pandianlist, PanDianListBean.DataBean.InfoBean.class);
                boolean ishas = false;
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getId().equals(bean.getId())) {
                        ishas = true;
                        break;
                    }
                }
                if (ishas == false) {
                    list.add(bean);
                    SharePrenceHelper.setInfo("pandian", JsonUtils.arrayToJson(list));

                }
            } catch (Exception e) {

            }
        }else {
            list.add(bean);
            try {
                SharePrenceHelper.setInfo("pandian", JsonUtils.arrayToJson(list));
            } catch (JsonUtils.JsonException e) {
                e.printStackTrace();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(PanDianEvent message) {
        pandianid = message.getId();
        EasyHttp.post(this)
                .api(new PanDianDetilsApi()
                        .setNoteId(message.getId()))
                .request(new HttpCallback<PanDianListBean>(this) {
                    @Override
                    public void onSucceed(PanDianListBean result) {
                        if (result.getData() != null && result.getData().getInfo() != null) {
                            orderId=result.getData().getInfo().getId();
                            mInventoryNumberView.setRightText(result.getData().getInfo().getOrderNo());
                            mMonthBarView.setRightText(result.getData().getInfo().getName());
                            mTypeBarView.setRightText(result.getData().getInfo().getDate());
                            savepandian(result.getData().getInfo());
                        }

                        if (result.getData() != null && result.getData().getRecord() != null) {

//                            if (ListUtils.getSize(result.getData().getInfo()) == 0) {
//                                TextView headView = mInventoryListView.addHeaderView(R.layout.picker_item);
//                                headView.setText("暂无物资数据");
//                                return;
//                            }

                            mInventoryDetailAdapter.clearData();
                            mInventoryDetailAdapter.setData(result.getData().getRecord());
                        }
                    }
                });
    }

    @SingleClick
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_scan_outbound) {
            XXPermissions.with(this)
                    .permission(Permission.CAMERA)
                    .permission(Permission.Group.STORAGE)
                    .request(new OnPermission() {
                        @Override
                        public void hasPermission(List<String> granted, boolean all) {
                            if (all) {
                                //跳转扫码页面
                                Intent intent = new Intent(PanDianListAct.this, QRCodeCaptureActivity.class);
                                intent.putExtra(QRCodeCaptureActivity.STATUS_BAR_COLOR, Color.parseColor("#99000000"));
                                startActivityForResult(intent, Constants.REQUEST_SCAN_CODE);
                            }
                        }

                        @Override
                        public void noPermission(List<String> denied, boolean quick) {
                            if (quick) {
                                toast(R.string.common_permission_fail);
                                XXPermissions.startPermissionActivity(getActivity(), false);
                            } else {
                                toast(R.string.common_permission_hint);
                            }
                        }
                    });
        }
    }

    //获取扫码结果
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_SCAN_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String result = null;
            if (bundle != null) {
                result = bundle.getString(QRCodeCaptureActivity.CODE_CONTENT);
                LogUtils.d(TAG, "-------- result-------- " + result);
            }
            if (TextUtils.isEmpty(result)) {
                toast("未识别到任何内容");
                return;
            }
             additem(result);
//            PanDianDetilsAct.start(this, result, "scan");
        }
    }
    private void additem(String result) {
        EasyHttp.post(this)
                .api(new InventoryMaterialApi()
                        .setCode(result)
                        .setGoodsId(orderId)
                        .setNum(1))
                .request(new HttpCallback<SimpleResultBean>(this) {
                    @Override
                    public void onSucceed(SimpleResultBean result) {
                        toast(result.getWarn());
                        if (result.getCode() == 1) {
                            postDelayed(() -> finish(), 1000);
                        }
                    }
                });
    }

    @Override
    public void onChildClick(RecyclerView recyclerView, View childView, int position) {
        if (recyclerView.equals(mInventoryListView)) {
            if (childView.getId() == R.id.btn_outbound) {
                PanDianDetilsAct.start(this, mInventoryDetailAdapter.getItem(position).getId(), "");
            }
        }
    }

    @Override
    public void onRightClick(View v) {
        if (ListUtils.getSize(mInventoryDetailAdapter.getData()) != 0) {
            new MessageDialog.Builder(this)
                    .setMessage("确定完成本次盘点吗？")
                    .setListener(dialog -> commitInventoryDatum()).show();
        } else {
            commitInventoryDatum();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 提交盘点
     */
    private void commitInventoryDatum() {
        if (pandianid != null) {
            EasyHttp.post(this)
                    .api(new InventoryCommitApi()
                            .setCheckId(pandianid))
                    .request(new HttpCallback<SimpleResultBean>(this) {
                        @Override
                        public void onSucceed(SimpleResultBean result) {
                            toast(result.getWarn());

                            if (result.getCode() == 1) {
                                delte(pandianid);
                                postDelayed(() -> finish(), 100);
                            }
                        }
                    });
        }
    }
    private void delte(String pandianid){
        List<PanDianListBean.DataBean.InfoBean> list=new ArrayList<>();
        String pandianlist = SharePrenceHelper.getStringData("pandian");
        if (pandianlist != null && !pandianlist.equals("")) {
            try {
                list = JsonUtils.jsonToArray(pandianlist, PanDianListBean.DataBean.InfoBean.class);
                boolean ishas = false;
                int first=0;
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getId().equals(pandianid)) {
                        ishas = true;
                        first=i;
                        break;
                    }
                }
                if (ishas == true) {
                    list.remove(first);
                    SharePrenceHelper.setInfo("pandian", JsonUtils.arrayToJson(list));
                }
            } catch (Exception e) {

            }
        }

    }
}
